export const toYmd = (d: Date): string => {
  const y = d.getUTCFullYear();
  const m = String(d.getUTCMonth() + 1).padStart(2, '0');
  const day = String(d.getUTCDate()).padStart(2, '0');
  return `${y}${m}${day}`;
};

export const ymdToDate = (ymd: string): Date => {
  const y = Number(ymd.slice(0, 4));
  const m = Number(ymd.slice(4, 6));
  const d = Number(ymd.slice(6, 8));
  return new Date(Date.UTC(y, m - 1, d));
};

export const ymdAddDays = (ymd: string, days: number): string => {
  const dt = ymdToDate(ymd);
  dt.setUTCDate(dt.getUTCDate() + days);
  return toYmd(dt);
};

export const todayYmd = (): string => toYmd(new Date());

export const fiveYearsAgoYmd = (): string => {
  const t = new Date();
  const d = new Date(Date.UTC(t.getUTCFullYear() - 5, t.getUTCMonth(), t.getUTCDate()));
  return toYmd(d);
};

export const sortByDateAsc = <T extends { trade_date: string }>(arr: T[]): T[] =>
  arr.sort((a, b) => a.trade_date.localeCompare(b.trade_date));